package com.jinxixin.android.recordvideo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.jinxixin.android.recordvideo.bean.MessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class TakePictureFinishActivity extends AppCompatActivity {
    private ImageView img_picture;
    private TextView tv_back;
    private TextView tv_confirm;

    public static void launch(Context context, String photoPath) {
        Intent intent = new Intent(context, TakePictureFinishActivity.class);
        intent.putExtra("data", photoPath);
        context.startActivity(intent);
    }

    private String mFilePath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_picture_finish);
        mFilePath = getIntent().getStringExtra("data");
        Bitmap bm = BitmapFactory.decodeFile(mFilePath);
        img_picture = findViewById(R.id.img_picture);
        img_picture.setImageBitmap(bm);
        tv_back = findViewById(R.id.tv_back);
        tv_confirm = findViewById(R.id.tv_confirm);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MessageEvent messageEvent = new MessageEvent(MessageEvent.FINISH_TAKE_PICTURE);
                messageEvent.setData(mFilePath);
                EventBus.getDefault().post(messageEvent);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getMsgCode() == MessageEvent.FINISH_RECORD_VIDEO) {
            finish();
        } else if (event.getMsgCode() == MessageEvent.FINISH_TAKE_PICTURE) {
            finish();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        //取消注册EventBus
        if (EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
